const express = require('express');
const router = express.Router();
const rds = require('../rds');
const logger = require('../logger');

// 问卷列表页面
router.get('/', async (req, res) => {
    try {
        const [surveys] = await rds.query(`
            SELECT 
                *,
                DATE_FORMAT(updated_at, '%Y-%m-%d %H:%i') as updated_at
            FROM eb_survey_list 
            ORDER BY add_time DESC
        `);

        res.render('survey/list', {
            surveys,
            title: '问卷管理',
            description: '管理调查问卷'
        });
    } catch (error) {
        logger.error('Error fetching surveys:', error);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取问卷列表失败',
            description: error.message
        });
    }
});

// 新建问卷页面
router.get('/new', (req, res) => {
    res.render("survey/edit", {
        survey: {
            program_code: "",
            title: "",
            source: "MTA",
            status: "OPEN",
            conditions: "u.status=1",
            description: "",
            entry_url: "",
            return_url: "",
            data_url: ""
        },
        isNew: true,
        title: "创建新问卷",
        description: "创建新的调查问卷"
    });
});

// 编辑问卷页面
router.get('/edit/:program_code', async (req, res) => {
    try {
        const { program_code } = req.params;
        const [surveys] = await rds.query(
            'SELECT * FROM eb_survey_list WHERE program_code = ?',
            [program_code]
        );

        if (surveys.length === 0) {
            return res.status(404).render("warn", {
                title: "未找到问卷",
                message: "该问卷不存在",
                description: `问卷代码: ${program_code}`
            });
        }

        res.render("survey/edit", {
            survey: surveys[0],
            isNew: false,
            title: "编辑问卷",
            description: `问卷代码: ${program_code}`
        });
    } catch (error) {
        logger.error("Error fetching survey details:", error);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取问卷详情失败',
            description: error.message
        });
    }
});

// 保存问卷信息
router.post('/', async (req, res) => {
    const connection = await rds.pool.getConnection();
    try {
        await connection.beginTransaction();

        const {
            program_code,
            title,
            source = 'MTA',
            status = 'OPEN',
            conditions = 'u.status=1',
            description = '',
            entry_url,
            return_url = '',
            data_url = '',
            isNew
        } = req.body;

        // 验证必填字段
        if (!program_code || !title || !entry_url) {
            throw new Error('问卷代码、名称和入口地址为必填项');
        }

        // 验证问卷代码格式
        if ( !/^SVY-\d{4}-\d{2}-\d{2}$/.test(program_code) && !/^CTR-\d{4}-\d{2}-\d{2}$/.test(program_code) ) {
            throw new Error('问卷代码格式不正确，应为SVY-YYYY-MM-DD格式');
        }

        const now = Math.floor(Date.now() / 1000);

        if (isNew === "true") {
            // 检查问卷代码是否已存在
            const [existing] = await connection.query(
                'SELECT 1 FROM eb_survey_list WHERE program_code = ?',
                [program_code]
            );

            if (existing.length > 0) {
                throw new Error('问卷代码已存在');
            }

            await connection.query(
                `INSERT INTO eb_survey_list 
                (program_id, program_code, title, source, status, conditions, 
                description, entry_url, return_url, data_url, add_time)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                [0, program_code, title, source, status, conditions,
                description, entry_url, return_url, data_url, now]
            );
        } else {
            await connection.query(
                `UPDATE eb_survey_list 
                SET title = ?, source = ?, status = ?, conditions = ?, 
                    description = ?, entry_url = ?, return_url = ?, data_url = ?
                WHERE program_code = ?`,
                [title, source, status, conditions, description,
                entry_url, return_url, data_url, program_code]
            );
        }

        await connection.commit();
        res.redirect("/apps/admin/surveys");
    } catch (error) {
        await connection.rollback();
        logger.error("Error saving survey:", error);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '保存问卷失败',
            description: error.message || '请检查必填字段是否填写完整'
        });
    } finally {
        connection.release();
    }
});

// 为旧的提交路径添加重定向
router.post('/survey', (req, res) => {
    res.redirect(307, '/apps/admin/surveys');
});

// 删除问卷
router.delete('/api/:program_code', async (req, res) => {
    const connection = await rds.pool.getConnection();
    try {
        await connection.beginTransaction();

        // 检查是否有答卷记录
        const [answers] = await connection.query(
            'SELECT 1 FROM eb_survey_answers WHERE program_code = ? LIMIT 1',
            [req.params.program_code]
        );

        if (answers.length > 0) {
            throw new Error('该问卷已有答卷记录，不能删除');
        }

        // 删除问卷
        await connection.query(
            'DELETE FROM eb_survey_list WHERE program_code = ?',
            [req.params.program_code]
        );

        await connection.commit();
        res.json({ success: true });
    } catch (error) {
        await connection.rollback();
        logger.error('Error deleting survey:', error);
        res.status(500).json({ error: error.message });
    } finally {
        connection.release();
    }
});

// 更新问卷状态
router.put('/api/:program_code/status', async (req, res) => {
    const connection = await rds.pool.getConnection();
    try {
        await connection.beginTransaction();

        const { status } = req.body;
        if (!['OPEN', 'CLOSED'].includes(status)) {
            throw new Error('无效的问卷状态');
        }

        await connection.query(
            'UPDATE eb_survey_list SET status = ? WHERE program_code = ?',
            [status, req.params.program_code]
        );

        await connection.commit();
        res.json({ success: true });
    } catch (error) {
        await connection.rollback();
        logger.error('Error updating survey status:', error);
        res.status(500).json({ error: error.message });
    } finally {
        connection.release();
    }
});

// 查看问卷结果
router.get('/results/:program_code', async (req, res) => {
    try {
        const { program_code } = req.params;
        const [survey] = await rds.query(
            'SELECT * FROM eb_survey_list WHERE program_code = ?',
            [program_code]
        );

        if (survey.length === 0) {
            return res.status(404).render('warn', {
                title: '问卷不存在',
                message: '未找到该问卷',
                description: `问卷代码: ${program_code}`
            });
        }

        // 如果有自定义数据查看地址，则重定向
        if (survey[0].data_url) {
            return res.redirect(survey[0].data_url);
        }

        // 否则查询本地数据库中的答卷记录
        const [results] = await rds.query(`
            SELECT 
                s.*,
                u.real_name,
                DATE_FORMAT(s.created_at, '%Y-%m-%d %H:%i') as submit_time
            FROM eb_survey_answers s
            LEFT JOIN eb_user u ON s.uid = u.uid
            WHERE s.program_code = ?
            ORDER BY s.created_at DESC
        `, [program_code]);

        res.render('survey/results', {
            survey: survey[0],
            results,
            title: '问卷结果',
            description: `${survey[0].title} - 答卷记录`
        });
    } catch (error) {
        logger.error('Error fetching survey results:', error);
        res.status(500).render('warn', {
            title: '系统错误',
            message: '获取问卷结果失败',
            description: error.message
        });
    }
});

module.exports = router; 
